package com.example.androidfinalproject.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.androidfinalproject.R;
import com.example.androidfinalproject.entity.DataItem;
import com.example.androidfinalproject.global.Global;
import com.example.androidfinalproject.utils.SerializeUtil;
import com.example.androidfinalproject.utils.StorageUtil;

import java.io.File;
import java.util.UUID;

public class PostActivity extends AppCompatActivity {
    private EditText title;
    private TextView detail;
    private EditText date;
    private EditText price;
    private EditText phone;
    private EditText url;
    //    private Button okBnt, cancelBnt;
    private DatePickerDialog datePicker;
    private Switch aSwitch;
    private ImageView imageView;
    private File file;
    private String fileName = UUID.randomUUID().toString();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cre_data_item);

        title = findViewById(R.id.PostTitle);
        detail = findViewById(R.id.detail);
        date = findViewById(R.id.BuyTime);
        price = findViewById(R.id.price);
        phone = findViewById(R.id.phone);
        url = findViewById(R.id.uri);
        //        okBnt = findViewById(R.id.ok);
        //        cancelBnt = findViewById(R.id.cancel);
        aSwitch = findViewById(R.id.switch1);
        imageView = findViewById(R.id.show2);

        file = getCacheDir();

        Toolbar toolbar = findViewById(R.id.toolbar4);
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        setSupportActionBar(toolbar);
        // 返回的点击事件
        toolbar.setNavigationOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setResult(RESULT_CANCELED);
                        finish();
                    }
                });

        // switch监听
        aSwitch.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            checkUrl(true);
                        }
                    }
                });

        // url的实时监听，当修改完毕并且已开启switch开关时判断url正确性
        url.setOnFocusChangeListener(
                new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (!hasFocus && aSwitch.isChecked()) {
                            checkUrl(false);
                        }
                    }
                });

        // 日历
        datePicker =
                new DatePickerDialog(
                        this,
                        new DatePickerDialog.OnDateSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onDateSet(
                                    DatePicker view, int year, int month, int dayOfMonth) {
                                date.setText(year + "/" + (month + 1) + "/" + dayOfMonth);
                            }
                        },
                        2000,
                        1,
                        1);
        // 搭配日历使用
        date.setOnFocusChangeListener(
                new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (hasFocus) {
                            datePicker.show();
                        }
                    }
                });

        //        // 发布按钮
        //        okBnt.setOnClickListener(
        //                new View.OnClickListener() {
        //                    @Override
        //                    public void onClick(View v) {}
        //                });
        //
        //        // 取消按钮
        //        cancelBnt.setOnClickListener(
        //                new View.OnClickListener() {
        //                    @Override
        //                    public void onClick(View v) {
        //                        setResult(RESULT_CANCELED);
        //                        finish();
        //                    }
        //                });
    }

    /** 检查输入的url正确性，若正确，加载到cache并显示到图片，若错误，提示输入错误 */
    private void checkUrl(boolean forSwitch) {
        if (url.getText().toString().equals("") && forSwitch) {
            Toast.makeText(getApplicationContext(), "请先输入图片url", Toast.LENGTH_SHORT).show();
            aSwitch.setChecked(false);
        } else {
            if (StorageUtil.downloadImage(file, fileName, url.getText().toString().trim())) {
                if (!StorageUtil.readImageFile(file, fileName, imageView)) {
                    Toast.makeText(this, "您输入的url有误，请重新检查！", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(PostActivity.this, "您输入的url有误，请重新检查！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.right_toolbar_menu, menu);

        MenuItem item = menu.findItem(R.id.right_action);
        item.setTitle("发布");
        item.setOnMenuItemClickListener(
                new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        String titleStr = title.getText().toString();
                        String priceStr = price.getText().toString();
                        String phoneStr = phone.getText().toString();
                        String detailStr = detail.getText().toString();
                        // 空串检查
                        if (titleStr.equals("") || priceStr.equals("") || phoneStr.equals("")) {
                            Toast.makeText(
                                            getApplicationContext(),
                                            "请检查输入是否有遗漏！",
                                            Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            String urlStr = url.getText().toString().trim();
                            if ("".equals(urlStr)
                                    || StorageUtil.downloadImage(file, fileName, urlStr)) {
                                DataItem dataItem =
                                        new DataItem(
                                                Global.getCurUserName(),
                                                titleStr,
                                                detailStr.equals("") ? null : detailStr,
                                                "".equals(urlStr) ? null : fileName,
                                                date.getText().toString(),
                                                Double.parseDouble(priceStr),
                                                phoneStr);
                                Bundle bundle = new Bundle();
                                bundle.putByteArray("data", SerializeUtil.serialize(dataItem));
                                Intent intent = new Intent();
                                intent.putExtras(bundle);
                                setResult(RESULT_OK, intent);
                                finish();
                            } else {
                                Toast.makeText(
                                                PostActivity.this,
                                                "您输入的url有误，请重新检查！",
                                                Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }

                        return true;
                    }
                });

        return super.onCreateOptionsMenu(menu);
    }
}
